<?php 

require_once '../Generique/header_complet.php';
require_once "../Securite/parser_chaines.php";

?>

<?php
	$notification="";
	$indiceA = 2;
	
	function adapterRequete( $text_requete )
	{
		if( isset( $_POST['chRating'] ) && $_POST['chRating'] != -1 )
		{
			$text_requete = $text_requete . ' AND dil_histoires.rating = ?';
			$_SESSION['chRating'] = $_POST['chRating'];
		}
		else
		{
			$_SESSION['chRating'] = -2;
		}
		
		if( isset( $_POST['chNiveau'] ) && $_POST['chNiveau'] != -1 )
		{
			if( $_POST['chNiveau'] == "2" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.niveau = 2';
			}
			else if( $_POST['chNiveau'] == "+50" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.niveau >= 50';
			}
			else if( $_POST['chNiveau'] == "2-5" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.niveau >= 2 AND dil_histoires.niveau <= 5';
			}
			else if( $_POST['chNiveau'] == "6-10" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.niveau >= 6 AND dil_histoires.niveau <= 10';
			}
			else if( $_POST['chNiveau'] == "11-20" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.niveau >= 11 AND dil_histoires.niveau <= 20';
			}
			else if( $_POST['chNiveau'] == "21-50" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.niveau >= 21 AND dil_histoires.niveau <= 5°';
			}
			
			$_SESSION['chNiveau'] = $_POST['chNiveau'];
		}
		else
		{
			$_SESSION['chNiveau'] = -2;
		}
		
		if( isset( $_POST['chChapitre'] ) && $_POST['chChapitre'] != -1 )
		{
			if( $_POST['chChapitre'] == "+60" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.taille >= 60';
			}
			else if( $_POST['chChapitre'] == "2-5" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.taille >= 2 AND dil_histoires.taille <= 5';
			}
			else if( $_POST['chChapitre'] == "6-10" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.taille >= 6 AND dil_histoires.taille <= 10';
			}
			else if( $_POST['chChapitre'] == "11-30" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.taille >= 11 AND dil_histoires.taille <= 30';
			}
			else if( $_POST['chChapitre'] == "31-60" )
			{
				$text_requete = $text_requete . ' AND dil_histoires.taille >= 31 AND dil_histoires.taille <= 50';
			}
			
			$_SESSION['chChapitre'] = $_POST['chChapitre'];
		}
		else
		{
			$_SESSION['chNiveau'] = -2;
		}
		
		return $text_requete;
	}
	
	function bindRequete( $requete , $indice )
	{
		if( isset( $_SESSION['chRating'] ) && $_SESSION['chRating'] != -2 )
		{
			$requete->bindValue( $indice , $_SESSION['chRating'] , PDO::PARAM_STR );
			$indice++;
		}
		
		return $indice;
	}
	
	
	
	
	if(isset ($_GET['idUnivers']) )
	{
		$_GET['idUnivers'] = securite_chaine($_GET['idUnivers']);

		$bdd = ouvrirBase();
		
		$nbHistoiresParPages = 5;
		
		//On crée un gestionnaire de pages pour afficher les informations souhaitées
		if(! univers_existe($_GET['idUnivers'], $bdd))
			$notification = "L'univers n'existe pas ";
			
		else
		{	
			// traitement d'une demande de mise en quarantaine
			if(isset($_POST['histoireQuarantaine'], $_SESSION['statut'], $_SESSION['nom'], $_POST['quarantaine'], $_POST['tokenQuarantaine'])
			&& verifierHistoire($bdd, $_POST['histoireQuarantaine']) &&
			verifier_token(600, 'Pages/histoire.php', 'ecriture_histoire', 'tokenQuarantaine') && 
			(verifierModerateurUnivers($bdd, $_GET['idUnivers'], $_SESSION['nom']))) 
			{	
				$req = $bdd->prepare("SELECT COUNT(*) FROM dil_histoiresenquarantaine WHERE idHistoire = :histoire ");
				$req->bindValue( 'histoire' , $_POST['histoireQuarantaine'], PDO::PARAM_INT);
				$req->execute();
				$result = $req->fetch();
				if($result['COUNT(*)']==0)
				{
					$req = $bdd->prepare("INSERT INTO dil_histoiresenquarantaine (idHistoire) Values (:histoire) ");
					$req->bindValue( 'histoire' , $_POST['histoireQuarantaine'], PDO::PARAM_INT);
					$req->execute();
				}
				else
					echo "l'histoire est déjà en quarantaine";
			}			
	
	
			$token = generer_token('ecriture_histoire');		
	   
			$text_requete = 'SELECT COUNT(*) FROM dil_histoires WHERE dil_histoires.nomUnivers = ? 
				AND id NOT IN (SELECT idHistoire FROM dil_histoiresenattentes)
				AND id NOT IN (SELECT idHistoire FROM dil_histoiresenquarantaine)';
			$text_requete = adapterRequete( $text_requete );
			$compte_histoires = $bdd->prepare( $text_requete );
			$compte_histoires->bindValue( 1 ,$_GET['idUnivers'], PDO::PARAM_INT);
			
			bindRequete( $compte_histoires , $indiceA );
			
			$compte_histoires->execute();
			
			$indiceA = 2;

			$nb_histoires = $compte_histoires->fetch();
			$nb_histoires = $nb_histoires['COUNT(*)'];
			$i = 1;
			$menuPage;

			$base_requete = 'SELECT dil_histoires.titre AS Nom,
												dil_histoires.Description AS Description,
												dil_histoires.id AS id,
												dil_histoires.premierePage AS premierePage,
												dil_histoires.pseudoAuteur AS Auteur,
												dil_histoires.rating AS Rating,
												dil_histoires.niveau AS Niveau,
												dil_histoires.taille AS Taille
												FROM dil_histoires
												WHERE dil_histoires.nomUnivers = ? 
												AND id NOT IN (SELECT idHistoire FROM dil_histoiresenattentes)
												AND id NOT IN (SELECT idHistoire FROM dil_histoiresenquarantaine)
												 ';
		   
		   $base_requete = adapterRequete( $base_requete );
		   
		   
		   if (floor(($nb_histoires-1)/$nbHistoiresParPages )> 0){
				$menuPage = "<br /><br />Pages  ";
		   
			   $page=1;
			   if(isset($_GET['page']) && is_numeric($_GET['page'])){
					$page = $_GET['page'];
					if($page  < 1 || $page > ceil($nb_histoires/$nbHistoiresParPages))
						$page=1;
						
				}
			   while (floor(($nb_histoires-1) / $nbHistoiresParPages)>= $i)
				{
					if($page == $i)
						$menuPage .= "$i | ";
					else
						$menuPage .= '<a href = "histoire.php?idUnivers='.$_GET['idUnivers'].'&page='.$i.'">'.$i.'</a> | ';
					$i += 1;
				}
				if($page == $i)
					$menuPage .= "$i<br /><br />";
				else 
					$menuPage .= '<a href = "histoire.php?idUnivers='.$_GET['idUnivers'].'&page='.$i.'">'.$i.'</a><br /><br />';
				
				 //On affiche la barre de gestion des pages
				echo $menuPage;
				
				
				
				$req = $bdd->prepare($base_requete.'LIMIT ? , ?'); 
				
				$indiceA = bindRequete( $req , $indiceA );
				
				$req->bindValue( $indice ,(($page-1)*$nbHistoiresParPages), PDO::PARAM_INT);
				$indiceA++;
				//On récupère les informations que l'on souhaite afficher sur la page actuelle
				if ($page == floor(($nb_histoires-1)/$nbHistoiresParPages) + 1)
				{
					$req->bindValue($indice,($nb_histoires - ($page-1)*$nbHistoiresParPages), PDO::PARAM_INT);
				}
				else
				{
					$req->bindValue($indice,$nbHistoiresParPages, PDO::PARAM_INT);
				}
				$indiceA++;
			}
			else
			{
				$req = $bdd->prepare($base_requete);
				bindRequete( $req , $indiceA );
			}
				
			$req->bindValue(1,$_GET['idUnivers'] , PDO::PARAM_INT);
			
			$req->execute();
			
			//on va chercher la banniere de l'univers pour la mettre en titre
			$reqBanniere = $bdd->prepare('SELECT dil_univers.skin AS Skin, dil_univers.nom as univ
						FROM dil_univers WHERE dil_univers.nom = :id' );
			$reqBanniere->bindValue('id',$_GET['idUnivers'], PDO::PARAM_INT);
			$reqBanniere->execute();				
			$banniere = $reqBanniere->fetch();
			
			//un clic sur la banniere renvoie vers la description de l'univers
			echo '<div class="banniere">';
				echo '<a href="descUnivers.php?idUnivers=' . $_GET['idUnivers'] . '">';
					echo '<img class="banniere" width="400px" src="'. $banniere['Skin'] . '" alt = "'.$banniere['univ'].'" />';
				echo '</a>';
			echo '</div>';
			
			// barre de recherche
			include "../Codes/barreDeRecherche.php";
			
			
			//On affiche les données selctionnées
						
			while( $donnees = $req->fetch() )
			{
				echo '<div class="requete">
					<table border="0px">
						<tr>
							';//case pour le rating
							echo '<td>
								<img src="../Images/Rating/rat_' . $donnees['Rating'] . '.png" alt="rating"/>
							</td>
							<td >
								<p>
									<b>' . $donnees['Nom'] . '</b><br/>
									'.$donnees['Description'] . '<br/> <i>';
									if( $donnees['Auteur'] !== "login")
									{
										echo '<a href="afficherLesHistoires.php?nom='. $donnees['Auteur'] . '">'. $donnees['Auteur'] . '</a></i><br/>';
									}
									else echo 'droits cédés aux modérateurs </i><br/>';
								echo'
								</p>
							</td>';
							echo '<td>
									</td>';
							echo '<td =>
									<p>
										Niveau : ' . $donnees['Niveau'] . '<br/>
										Nb Chapitres : ' . $donnees['Taille'] . '
									</p>
								</td>';
						//boutons jouer, explorer et modifier
						echo '<td >';
							//jouer
							
							if($donnees['premierePage']>=0)
							{
								echo '<a href="chapitre.php?numero=' . $donnees['premierePage'] .'">';
									echo '<input class="max" type="button" value="Jouer" name="Jouer" />';
								echo '</a>';
							}
							//explorer
							echo '<a href="hierarchie.php?idHistoire=' . $donnees['id'] . '">';
								echo '<input class="max" type="button" value="Explorer" name="Explorer" />';
							echo '</a>';
							//modifier
							//on ne peut modifier l'histoire que si l'on est un modérateur de l'univers, administrateur ou le créateur de l'histoire
							//pareil pour la mise en quarantaine...
							if( verifierAuteurHistoire( $bdd , $donnees['id'] ) )
							{
								echo '<a href="modifHistoire.php?idHistoire=' . $donnees['id'] . '&amp;token='.$token.'">';
									echo '<input class="max" type="button" value="Modifier" name="Modifier" />';
								echo '</a>';
							}
							
							if(isset($_SESSION['statut'], $_SESSION['nom']) && ($_SESSION['statut']=="administrateur" ||
								verifierModerateurUnivers($bdd, $_GET['idUnivers'], $_SESSION['nom'])) )
							{?>
								<form method = "post" action = "">
								<div>
									<input type = "submit" class="max" name = "quarantaine" value = "supprimer" />
									<input type = "hidden" name = "histoireQuarantaine" value = "<?php echo $donnees['id']; ?>"/>
									<input type = "hidden" name = "tokenQuarantaine" value = "<?php echo $token; ?>"/>
								</div>
								</form>
							<?php
							}
						echo '</td>';
					echo '</tr>';
				echo '</table>';
			echo '</div>';
			}
			
			//On affiche la barre de gestion des pages
			if (floor(($nb_histoires-1)/$nbHistoiresParPages )> 0)
				echo $menuPage;
			
			if(isset($_SESSION['statut']) && ($_SESSION['statut'] == "moderateur" || $_SESSION['statut'] == "administrateur") )
			{
				$_SESSION['modeCreationHistoire'] = 1;
				?>
				<div>
				<p style="text-align:center;"><a href="ajoutHistoire.php?univers=<?php echo $_GET['idUnivers']; ?>">Ajout d'une nouvelle Histoire</a></p>
				</div>
				<?php
			}
			else if( isset($_SESSION['statut']))
			{
				$_SESSION['modeCreationHistoire'] = 0;
				?>
				<div>
				<p style="text-align:center;"><a href="ajoutHistoire.php?univers=<?php echo $_GET['idUnivers']; ?>">Proposer une nouvelle Histoire</a></p>
				</div>
				<?php
			}
			
			echo '<div style="text-align:center;"> <a href="descUnivers.php?idUnivers=' . $_GET['idUnivers'] . '">
				<input style="width=200px;" type="button" value="Description de l\'univers" name="Description de l\'univers" />
			</a></div>';
		}
	//ZONE DE NOTIFICATION : pour l'affichage des différentes notifications
	echo '<div id="notification">
	'.$notification.'
	</div>';
	}
	
include("../Generique/pied.php"); ?>
